package gui;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.postgresql.util.PSQLException;

import util.SearchDatabase;
import base.MovieDetails;
import base.MovieInfo;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

import database.ConnectionDB;

/**
 * <a href="JSPPortlet.java.html"><b><i>View Source</i></b></a>
 *
 * @author linhnt
 *
 */
public class UserInterface extends MVCPortlet {
	
	protected String viewJSP;
	protected String searchResultJSP;
	protected String changeJSP;
	protected String updateJSP;
	public void init() throws PortletException {
		viewJSP = getInitParameter("view-jsp");
		searchResultJSP = getInitParameter("searchResult-jsp");
		updateJSP = getInitParameter("update-jsp");
	}

	public void doDispatch(RenderRequest renderRequest, RenderResponse renderResponse)throws IOException, PortletException {
		String jspPage = renderRequest.getParameter("jspPage");
		if (jspPage != null) {
			include(jspPage, renderRequest, renderResponse);
		}
		else {
			super.doDispatch(renderRequest, renderResponse);
		}
	}
	public void doView(RenderRequest renderRequest, RenderResponse renderResponse)throws IOException, PortletException {
		String nextView = renderRequest.getParameter("nextView");
		if (nextView == null || nextView.equals("")){
			// 1. Generate all movie records in database.
			try {
				renderRequest.setAttribute("movieList",new ConnectionDB().SelectAll());
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			include(viewJSP, renderRequest, renderResponse);
		}else if(nextView.equals("searchresultForm")){
			// nextView para changed from view.jsp to search.jsp
			// Purpose: Go to "result" page from searching information, then user can choose add it in Database or not.
			include(searchResultJSP, renderRequest, renderResponse);
		}else if(nextView.equals("updateForm")){
			//Nextview parameter changed from view.jsp to update.jsp
			include(updateJSP, renderRequest, renderResponse);
		}
	}

	public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException, PortletException {
		super.processAction(actionRequest, actionResponse);
	}
	
	public void InsertAction(ActionRequest actionRequest, ActionResponse actionResponse) throws ClassNotFoundException, SQLException, IOException, PortletException{
		String movieTitle = actionRequest.getParameter("movieTitle");
		String movieGenre = actionRequest.getParameter("movieGenre");
		String movieYear = actionRequest.getParameter("movieYear");
		String movieCountry = actionRequest.getParameter("movieCountry");
		String movieLanguages = actionRequest.getParameter("movieLanguages");
		String movieRating = actionRequest.getParameter("movieRating");
		String movieVotes = actionRequest.getParameter("movieVotes");
		String movieLink = actionRequest.getParameter("movieLink");
		if (isInvalid(movieTitle) || isInvalid(movieGenre) || isInvalid(movieYear)){
			actionResponse.setRenderParameter("msg", "Please fill all the form");
		}else{
			MovieInfo movieInfo = new MovieInfo();
			MovieDetails movieDetails = new MovieDetails(); 
			movieInfo.setTitle(movieTitle);
			movieInfo.setGenre(movieGenre);
			movieInfo.setYear(movieYear);
			movieDetails.setCountry(movieCountry);
			movieDetails.setLanguages(movieLanguages);
			movieDetails.setRating(movieRating);
			movieDetails.setNumberofVotes(movieVotes);
			movieDetails.setLinkToIMDB(movieLink);
			movieInfo.setDetails(movieDetails);
			try {
				new ConnectionDB().Insert(movieInfo);
			} catch (PSQLException e) {
//				e.printStackTrace();
			}
			actionResponse.setRenderParameter("msg", "Insert Successfully");
		}
		actionResponse.setRenderParameter("nextView", "");
	}
	
	public boolean isInvalid(String tmp){
		if (tmp !=null && !tmp.equals("")){
			return false;
		}
		return true;
	}
	
	public void ChangeAction(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException, PortletException, ClassNotFoundException, SQLException {
		Enumeration<String> names = actionRequest.getParameterNames();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			StringBuffer sb = new StringBuffer(name);
			if (sb.indexOf("movieDeleteId") > -1){ // means not NULL
				sb.delete(0, "movieDeleteId".length());
				new ConnectionDB().Delete(sb.toString());
				actionResponse.setRenderParameter("msg", "Delete record successfully");
				actionResponse.setRenderParameter("nextView", "");
			}else if (sb.indexOf("movieDetailId") > -1){ // means not NULL
				sb.delete(0, "movieDetailId".length());
				MovieInfo movieInfo = new ConnectionDB().Select(sb.toString());
				MovieDetails movieDetails = movieInfo.getDetails();
				actionResponse.setRenderParameter("movieId", "" + movieInfo.getMovieId());
				actionResponse.setRenderParameter("movieTitle", movieInfo.getTitle());
				actionResponse.setRenderParameter("movieGenre", movieInfo.getGenre());
				actionResponse.setRenderParameter("movieYear", movieInfo.getYear());
				actionResponse.setRenderParameter("movieCountry", movieDetails.getCountry());
				actionResponse.setRenderParameter("movieLanguages", movieDetails.getLanguages());
				actionResponse.setRenderParameter("movieRating", movieDetails.getRating());
				actionResponse.setRenderParameter("movieVotes", movieDetails.getNumberofVotes());
				actionResponse.setRenderParameter("movieLink", movieDetails.getLinkToIMDB());
				actionResponse.setRenderParameter("nextView", "updateForm");
			}
		}
	}
	
	public void DeleteAllAction(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException, PortletException, ClassNotFoundException, SQLException {
//		actionResponse.setRenderParameter("nextView", "updateForm");
	}
	
	public void UpdateAction(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException, PortletException, ClassNotFoundException, SQLException {
		MovieInfo movieInfo = new MovieInfo();
		MovieDetails movieDetails = new MovieDetails(); 
		try {
			
			//Step 1: GET NEW INFORMATION FROM UI -> PUT INTO an Object
			
			String movieId = actionRequest.getParameter("movieId");
			String movieGenre = actionRequest.getParameter("movieGenre");
			String movieYear = actionRequest.getParameter("movieYear");
			String movieCountry = actionRequest.getParameter("movieCountry");
			String movieLanguages = actionRequest.getParameter("movieLanguages");
			String movieRating = actionRequest.getParameter("movieRating");
			String movieVotes = actionRequest.getParameter("movieVotes");
			String movieLink = actionRequest.getParameter("movieLink");
			if (isInvalid(movieGenre) || isInvalid(movieYear)){
				actionResponse.setRenderParameter("msg", "Please fill all the form or at least Genre and Year fields");
			}else{
				movieInfo.setMovieId(Integer.parseInt(movieId));
				movieInfo.setGenre(movieGenre);
				movieInfo.setYear(movieYear);
				movieDetails.setCountry(movieCountry);
				movieDetails.setLanguages(movieLanguages);
				movieDetails.setRating(movieRating);
				movieDetails.setNumberofVotes(movieVotes);
				movieDetails.setLinkToIMDB(movieLink);
				movieInfo.setDetails(movieDetails);
			}
			
			//Step 2 SEND DATA TO UPDATE IN DATABASE
			
			new ConnectionDB().Update(movieInfo);
			actionResponse.setRenderParameter("movieTitle", movieInfo.getTitle());
			actionResponse.setRenderParameter("movieGenre", movieInfo.getGenre());
			actionResponse.setRenderParameter("movieYear", movieInfo.getYear());
			actionResponse.setRenderParameter("movieCountry", movieDetails.getCountry());
			actionResponse.setRenderParameter("movieLanguages", movieDetails.getLanguages());
			actionResponse.setRenderParameter("movieRating", movieDetails.getRating());
			actionResponse.setRenderParameter("movieVotes", movieDetails.getNumberofVotes());
			actionResponse.setRenderParameter("movieLink", movieDetails.getLinkToIMDB());
			actionResponse.setRenderParameter("msg", "Update Successfully");
			actionResponse.setRenderParameter("nextView", "updateForm");
		} catch (PSQLException e) {
//			e.printStackTrace();
//			actionResponse.setRenderParameter("nextView", "");
		}catch(Exception e){
			e.printStackTrace();
			actionResponse.setRenderParameter("nextView", "");
		}
	}
	
	public void SearchAction(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException, PortletException {
		String movieTitleInput = actionRequest.getParameter("movieTitleInput");
		String movieYearInput = actionRequest.getParameter("movieYearInput");
		if (isInvalid(movieTitleInput)){
			actionResponse.setRenderParameter("msg", "Please fill Movie Title");
			actionResponse.setRenderParameter("nextView", "");
		}else{
			MovieInfo movieInfo = new SearchDatabase(movieTitleInput, movieYearInput).Search();
			if (!isInvalid(movieInfo.getError())){
				actionResponse.setRenderParameter("msg", "Film not found");
				actionResponse.setRenderParameter("nextView", "");
			}else {
				MovieDetails movieDetails = movieInfo.getDetails();
				actionResponse.setRenderParameter("movieTitle", movieInfo.getTitle());
				actionResponse.setRenderParameter("movieGenre", movieInfo.getGenre());
				actionResponse.setRenderParameter("movieYear", movieInfo.getYear());
				actionResponse.setRenderParameter("movieCountry", movieDetails.getCountry());
				actionResponse.setRenderParameter("movieLanguages", movieDetails.getLanguages());
				actionResponse.setRenderParameter("movieRating", movieDetails.getRating());
				actionResponse.setRenderParameter("movieVotes", movieDetails.getNumberofVotes());
				actionResponse.setRenderParameter("movieLink", movieDetails.getLinkToIMDB());
				actionResponse.setRenderParameter("nextView", "searchresultForm");
			}
		}
	}

	protected void include(String path, RenderRequest renderRequest,RenderResponse renderResponse)	throws IOException, PortletException {

		PortletRequestDispatcher portletRequestDispatcher =	getPortletContext().getRequestDispatcher(path);
		if (portletRequestDispatcher == null) {
			_log.error(path + " is not a valid include");
		} else {
			portletRequestDispatcher.include(renderRequest, renderResponse);
		}
	}
	
	private static Log _log = LogFactoryUtil.getLog(UserInterface.class);
}